package com.huoshan.im.server.utils;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;


public class JsonUtils {

    private static final Gson GSON = new GsonBuilder()
            .registerTypeAdapter(Date.class, new DateAdepter())
//            .setPrettyPrinting() // 换行输出
            .create();

    public static String toJson(Object obj) {
        return GSON.toJson(obj);
    }

    public static String toJsonWithNull(Object obj) {
        Gson gson = new GsonBuilder().serializeNulls().create();
        return gson.toJson(obj);
    }

    public static <T> T fromJson(String json, Class<T> tClass) {
        return GSON.fromJson(json, tClass);
    }

    private static class DateAdepter implements JsonDeserializer<Date>, JsonSerializer<Date> {

        @Override
        public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
            Date date = null;
            try {
                String val = jsonElement.getAsString();
                if (val.indexOf("-") > 0) {
                    if (val.indexOf(".") > 0)
                        date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(val);
                    else if (val.indexOf(":") > 0)
                        date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(val);
                    else
                        date = new SimpleDateFormat("yyyy-MM-dd").parse(val);
                } else {
                    date = new Date(Long.parseLong(val));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return date;
        }

        @Override
        public JsonElement serialize(Date date, Type type, JsonSerializationContext jsonSerializationContext) {
            if (date == null) return new JsonPrimitive("");
            return new JsonPrimitive(date.getTime());
        }

    }

}
